package com.lwc.backendsinglestructure.service.impl;
import com.lwc.backendsinglestructure.service.MailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.HashMap;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 用来发送模版邮件
     */
    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendTemplateMail(String to, String subject, String templateName, String code) {
        try {
            HashMap<String, Object> variables = new HashMap<>();
            variables.put("code", code);
            Context context = new Context();
            context.setVariables(variables);
            // 渲染模板 verification-code是模板文件的名称 一般放在 resource/templates 文件夹下
            String emailContent = templateEngine.process("verification-code", context);

            // 创建邮件
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            // 发送者
            helper.setFrom(from);
            // 发给谁
            helper.setTo(to);
            // 发送主题
            helper.setSubject(subject);
            // 发送的文本 渲染后的html
            helper.setText(emailContent, true); // true 表示HTML内容
            mailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("模板邮件发送失败", e);
        }
    }
}
